<template>
  <div class="page-container">
    <el-form inline>
      <el-form-item label="用户ID">
        <el-input v-model="roomParams.user_id" placeholder="用户ID" disabled></el-input>
      </el-form-item>
      <el-form-item label="房间号">
        <el-input v-model="roomParams.room_code" placeholder="请输入房间号"></el-input>
      </el-form-item>
      <el-form-item label="">
        <el-button type="primary" @click="handleJoinRoom">加入房间</el-button>
        <el-button type="primary" @click="handleCreateRoom">创建房间</el-button>
      </el-form-item>
    </el-form>

    <div class="chat_container">
      <div class="user_list">
        <el-table
          :data="webrtcStore.userList"
          @row-click="handleRowClick"
          highlight-current-row
        >
          <el-table-column label="用户ID">
            <template #default="scope">
              {{ scope.row }}
            </template>
          </el-table-column>
          <el-table-column label="连接状态">
            <template #default="scope">
              {{
                webrtcStore.connections[scope.row] != null
                  ? webrtcStore.connections[scope.row].status
                  : ""
              }}
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="chat_window">
        <div class="chat_window_title">{{ selectedTargetUser }}</div>
        <div class="chat_window_body">
          <div
            :class="
              item.userName === roomParams.user_id ? 'chat_message_right' : 'chat_message'
            "
            v-for="item of chatMessages"
            :key="item.messageId"
          >
            <div class="user_name">
              {{ item.userName }}
            </div>
            <div class="message_content">
              <div v-if="item.type == 'file'">
                {{ item.data.fileName }} {{ formatFileSize(item.data.fileSize) }}
                <el-progress
                  :percentage="item.data.progress"
                  :show-text="true"
                  :height="10"
                  :stroke-width="10"
                />
              </div>
            </div>
          </div>
        </div>
        <div class="chat_window_footer">
          <div class="toolbar">
            <el-upload
              class="file-upload"
              action="#"
              :auto-upload="false"
              :on-change="handleFileSelect"
              :show-file-list="false"
            >
              <el-icon class="file-icon"><Folder /></el-icon>
            </el-upload>
          </div>
          <div class="text_content">
            <!-- <el-input
              v-model="message"
              type="textarea"
              rows="8"
              placeholder="请输入消息"
            /> -->
          </div>
          <div class="send_button_bar">
            <el-button type="primary" @click="handleSendMessage">发送</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import initSocket from "@/utils/socket.js";
import emitter from "@/utils/eventBus.js";
import { ElMessageBox, ElMessage } from "element-plus";
import { ref } from "vue";
import { Folder } from "@element-plus/icons-vue";
import { useWebRtcStore } from "@/stores/webrtc.js";
const webrtcStore = useWebRtcStore();
import { v4 as uuidv4 } from "uuid";
const chatMessages = ref([]);

let socket = null;
const roomParams = ref({
  room_code: null,
  user_id: null,
});
async function handleCreateRoom() {
  socket.emit("create_room", (res) => {
    roomParams.value.room_code = res.room_code;
    ElMessage({
      type: "success",
      message: "创建房间成功",
    });
  });
}
function handleJoinRoom() {
  if (!roomParams.value.room_code) {
    ElMessageBox.alert("请输入房间号", "提示", {
      confirmButtonText: "确定",
      type: "warning",
    });
    return;
  }
  socket.emit(
    "join_room",
    {
      room_code: roomParams.value.room_code,
      user_id: roomParams.value.user_id,
    },
    (res) => {
      if (res != null) {
        ElMessage({
          type: "success",
          message: "加入房间成功",
        });
        webrtcStore.setUserList(res.users);
      }
    }
  );
}

function handleRowClick(row) {
  if (row == roomParams.value.user_id) {
    return;
  }
  selectedTargetUser.value = row; // 选中目标用户
  webrtcStore.connectTo({
    targetUserId: row,
    roomCode: roomParams.value.room_code,
  });
}

async function initWebSocket() {
  // 消息事件总线
  socket = await initSocket({
    url: `/ws`,
    onMessage: (res) => {
      switch (res.event) {
        case "room_error":
          ElMessage({
            type: "error",
            message: res.message,
          });
          break;
        case "signal_error":
          ElMessage({
            type: "error",
            message: res.message,
          });
          break;
        case "user_joined":
          webrtcStore.setUserList(res.data.users);
          break;
        case "user_left":
          webrtcStore.setUserList(res.data.users);
          break;
        case "signal":
          webrtcStore.handleSignal(res.data);
          break;
      }
    },
  });
  roomParams.value.user_id = socket.id;
  return socket;
}
function onWebRtcMessage(info) {
  // message = {
  //   type: "file_metadata",
  //   fileId,
  //   fileName,
  //   totalChunks,
  //   fileSize: file.size,
  //   userId: this.currentUserId,
  // };

  if (info.type === "file_metadata") {
    chatMessages.value.push({
      userName: info.userId,
      messageId: uuidv4(),
      type: "file",
      data: {
        ...info,
        progress: 0,
      },
    });
  }
}
function onReceiveProgress(info) {
  const { fileId, progress } = info;
  chatMessages.value.find(
    (x) => x.type == "file" && x.data.fileId === fileId
  ).data.progress = progress;
}

onMounted(async () => {
  await initWebSocket();
  webrtcStore.init(socket, onWebRtcMessage, onReceiveProgress);
});

// 新增文件传输相关变量
const selectedFile = ref(null);
const selectedTargetUser = ref(null);

// 处理文件选择
function handleFileSelect(file) {
  selectedFile.value = file.raw; // 保存原始文件对象
  sendFile();
}

// 格式化文件大小显示
function formatFileSize(bytes) {
  if (bytes < 1024) return bytes + " B";
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + " KB";
  if (bytes < 1024 * 1024 * 1024) return (bytes / (1024 * 1024)).toFixed(2) + " MB";
  return (bytes / (1024 * 1024 * 1024)).toFixed(2) + " GB";
}

const tranferFiles = ref([]);

// 发送文件（需先在用户列表中选择目标用户）
function sendFile() {
  if (!selectedFile.value || !selectedTargetUser.value) return;

  // 调用store中的文件发送方法
  webrtcStore.sendFile({
    targetUserId: selectedTargetUser.value,
    file: selectedFile.value,
    onBeginSend: (info) => {
      console.log("开始发送文件", info.fileId);
      chatMessages.value.push({
        userName: roomParams.value.user_id,
        messageId: uuidv4(),
        type: "file",
        data: {
          ...info,
          progress: 0,
        },
      });
      tranferFiles.value.push(info);
    },
    onSendProgress: (info) => {
      const { fileId, progress } = info;
      const index = tranferFiles.value.findIndex((item) => item.fileId === fileId);
      if (index !== -1) {
        tranferFiles.value[index].progress = progress;
        chatMessages.value.find(
          (x) => x.type == "file" && x.data.fileId === fileId
        ).data.progress = progress;
      }
      console.log("文件发送进度", fileId, progress);
    },
  });
}

function handleSendMessage() {}
</script>
<style lang="scss" scoped>
.file-icon {
  font-size: 28px;
}
.chat_container {
  height: 80%;
  width: 100%;
  display: flex;
  .user_list {
    width: 400px;
    height: 100%;
    border: 1px solid #d5d5d5;
  }
  .chat_window {
    flex: 1;
    height: 100%;
    display: flex;
    flex-direction: column;
    border: 1px solid #d5d5d5;
    border-left: 0;
    .chat_window_title {
      height: 68px;
      line-height: 68px;
      color: #303133;
      background-color: #f5f7fa;
      border-bottom: 1px solid #d5d5d5;
      padding-left: 25px;
    }
    .chat_window_body {
      flex: 1;
      width: 100%;
      padding: 20px;
      overflow-y: auto; /* 设置内容超出时显示竖向滚动条 */
      .chat_message {
        display: flex;
        flex-direction: row;
        width: 60%;
        margin-bottom: 15px;

        .user_name {
          width: 100px;
          height: 100px;
          border: 1px solid #d5d5d5;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: normal;
          word-wrap: break-word;
          margin-right: 20px;
          padding: 5px;
        }
        .message_content {
          flex: 1;
          background: #ffffff;
          padding: 5px 15px;
          position: relative;
          border-radius: 5px;
          &:before {
            content: " ";
            width: 0;
            height: 0;
            border-top: 5px solid transparent;
            border-bottom: 5px solid transparent;
            border-right: 10px solid #ffffff;
            position: absolute;
            left: -10px;
            top: 50%;
            transform: translateY(-50%);
          }
        }
      }

      .chat_message_right {
        /* 新增的右对齐样式 */
        display: flex;
        flex-direction: row-reverse;
        width: 60%;
        margin-left: auto;
        margin-bottom: 15px;
        .user_name {
          width: 100px;
          height: 100px;
          border: 1px solid #d5d5d5;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: normal;
          word-wrap: break-word;
          margin-left: 20px;
          margin-right: 0;
          padding: 5px;
          text-align: right;
        }
        .message_content {
          flex: 1;
          background: #9eea6a; /* 微信自己消息的绿色背景 */
          padding: 5px 15px;
          position: relative;
          border-radius: 5px;
          &:before {
            content: " ";
            width: 0;
            height: 0;
            border-top: 5px solid transparent;
            border-bottom: 5px solid transparent;
            border-left: 10px solid #9eea6a;
            position: absolute;
            right: -10px;
            top: 50%;
            transform: translateY(-50%);
          }
        }
      }
    }
    .chat_window_footer {
      border-top: 1px solid #d5d5d5;
      height: 280px;
      display: flex;
      flex-direction: column;
      .toolbar {
        height: 50px;
        display: flex;
        align-items: center;
        // justify-content: center;
        padding: 0 25px;
        .file-upload {
          display: flex;
          align-items: center;
        }
      }
      .text_content {
        flex: 1;
        display: flex;
        flex-direction: column;
        height: 100%;
        padding: 0 15px;
      }
      .send_button_bar {
        height: 50px;
        line-height: 50px;
        text-align: right;
        padding-right: 15px;
      }
    }
  }
}
</style>
